package com.aaa.controller.login;

import com.aaa.entity.ResponseDto;
import com.aaa.entity.Staff;
import com.aaa.service.StaffService;
import com.aaa.service.impl.StaffServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    StaffService staffService ;


    @Override
    public void init() throws ServletException {
        // 一定要把service 卸载init（） 方法，这样初始化一次，如果写doGet里面 每次调用创建，都很耗费时间
        staffService = new StaffServiceImpl();
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String staffId = req.getParameter("loginName");
        String password = req.getParameter("loginPwd");

        System.out.println(staffId + "  " +password);

        ResponseDto responseDto = new ResponseDto();

        try {
            Staff staff =  staffService.login(staffId,password);
            System.out.println(staff+"sssss");
            if (staff!=null){  // 判断是否有这个员工
                responseDto.setStatus(ResponseDto.SUCCESS_CODE);
                responseDto.setData(staff);
                responseDto.setMessage("请求成功");
            }else {
                responseDto.setStatus(ResponseDto.FAILURE_CODE);
                responseDto.setMessage("不存在该用户");
            }

        } catch (Exception e) {  // 将所有java 代码的错误处理，不会返回给前端界面
            e.printStackTrace();
            responseDto.setStatus(ResponseDto.FAILURE_CODE);
            responseDto.setMessage(e.getMessage());
            responseDto.setMessage("请求失败");
        }

        // 返回序列化的数据
        resp.getWriter().write(new Gson().toJson(responseDto));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }

}
